class Topics < Controller
    helper :forum_functions
    map '/topic'
    
    def index(topic_id)
        topic = get_topic(topic_id)
        @topic_id = topic.id
        @posts = topic.posts
        
        @forum_path = forum_path(topic.forum, topic)
    end
    
    def show(topic_id)
        topic = get_topic(topic_id)
        @topic_name = topic.name
        @topic_href = r(:index, topic_id)
        @topic_size = topic.post_count
    end
    
    def new
        require_login
        
        if request.get?
            forum = get_forum(request[:forum_id])
            @forum_id = forum.id
            @forum_name = forum.name
        else
            redirect Forums.r(:index)
        end
    end
    
    def create
        require_login
        
        if request.post?
            forum = get_forum(request[:forum_id])
            
            topic = Topic.new(
                :name => request[:name].esc,
                :forum => forum
            )
            
            topic.save
            
            post = Post.new(
                :user => user,
                :content => request[:content].esc,
                :topic => topic
            )
            
            post.save
            
            redirect r(:index, topic.id)
        end
    end
    
    def delete(topic_id)
        topic = get_topic(topic_id)
        forum = topic.forum
        topic.delete
        
        flash[:message] = "Le sujet a été supprimé"
        redirect Forums.r(:index, forum.id)
    end
    
    def edit(topic_id)
        # Uncomplete
        redirect r(:index, topic_id)
        
        require_login
        
        @forum_id = forum.id
        @forum_name = forum.name
        
        topic = get_topic(topic_id)
        @topic_id = topic.id
        @topic_name = topic.name
        
        forum = topic.forum
        @forum_id = forum.id
        @forum_name = forum.name
    end
    
    def save(topic_id)
        # Uncomplete
        redirect r(:index, topic_id)
        
        topic = get_topic(topic_id)
        topic.update(
            :name => request[:name].esc
        )
        topic.save
    end
    
end
